﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace NthDownload.Common.Utils
{
    public class XmlUtils
    {
        /// <summary>
        /// Gets a value form the first decendant of a particular name from an XDocument
        /// </summary>
        /// <param name="document">The document which to search.</param>
        /// <param name="decendantElementName">The name of the decendant for which to search</param>
        public static XElement GetDecendant(XDocument document, string decendantElementName)
        {
            IEnumerable<XElement> decendants = document.Descendants(decendantElementName);

            if (!decendants.Any())
            {
                return null;
            }

            return decendants.ElementAt(0);
        }

        /// <summary>
        /// Gets a value form the first decendant of a particular name from an XElement
        /// </summary>
        /// <param name="element">The element which to search.</param>
        /// <param name="decendantElementName">The name of the decendant for which to search</param>
        public static XElement GetDecendant(XElement element, string decendantElementName)
        {
            IEnumerable<XElement> decendants = element.Descendants(decendantElementName);

            if (!decendants.Any())
            {
                return null;
            }

            return decendants.ElementAt(0);
        }

        /// <summary>
        /// Adds a new XElement to an existing XElement
        /// </summary>
        /// <param name="existingElement">The exiting XElement.</param>
        /// <param name="newElementName">The name of the child XElement to be created.</param>
        /// <param name="newElementContent">The value of the child XElement to be created.</param>
        public static XElement AddElementToElement(XElement existingElement, string newElementName, object newElementContent)
        {
            XElement newElement = new XElement(newElementName, newElementContent);
            existingElement.Add(newElement);
            return newElement;
        }
    }
}
